package com.deep.sso.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * server控制器
 *
 * @author Deep
 * @date 2022/2/8
 */
@Controller
public class ServerController {

    @Autowired
    private RedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/")
    public String serverHello() {
        return "login";
    }

    //    redirect:http://ssoserver.com:8080/login.html?redirect_url=http://ssoclient1.com:8081/employees
    @GetMapping(value = "/login.html")
    public String login(@RequestParam(value = "redirect_url") String url,
                        Model model,
                        @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (sso_token != null) {
            // 已登录
            return "redirect:" + url + "?token=" + sso_token;   // 重定向回url另加token
        }
        // 未登录
        model.addAttribute("url", url);     // 将client端url作为参数放入model
        return "login";
    }

    @PostMapping(value = "/doLogin")
    public String doLogin(String username,
                          String password,
                          String url,
                          HttpServletResponse response) {

        if (username != null && password != null) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 登录成功跳转，跳回到之前的页面
            redisTemplate.opsForValue().set(uuid, username, 10, TimeUnit.MINUTES);
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + uuid;
        }
        return "/";
    }
}
